<template>
  <!---搜索表单-->
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item label="分类" placeholder="请选择">
            <el-cascader
              :props="categoryProps"
              style="width: 100%"
              v-model="searchCategoryIdList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品牌">
            <el-select v-model="queryDto.brandId">
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="searchCategoryBrand">
          搜索
        </el-button>
        <el-button size="small" @click="resetData">重置</el-button>
      </el-row>
    </el-form>
  </div>
  <!--添加按钮-->
  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow">添 加</el-button>
  </div>
  <!-- 添加表单 -->
  <el-dialog v-model="dialogVisible" :title="title" width="40%">
    <el-form label-width="120px">
      <el-form-item label="分类名称">
        <el-cascader
          :props="categoryProps"
          style="width: 100%"
          v-model="categoryBrand.categoryId"
        />
      </el-form-item>
      <el-form-item label="品牌名称">
        <el-select v-model="categoryBrand.brandId">
          <el-option
            v-for="item in brandList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!---数据展示表格-->
  <el-table :data="list" style="width: 100%" stripe="true">
    <el-table-column prop="categoryName" label="分类名称" />
    <el-table-column prop="brandName" label="品牌名称" />
    <el-table-column prop="logo" label="Logo" #default="scope">
      <img :src="scope.row.logo" width="50" />
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column label="操作" #default="scope" align="center" width="280">
      <el-button type="primary" size="small" @click="updateShow(scope.row)">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="remove(scope.row)">
        删除
      </el-button>
    </el-table-column>
  </el-table>

  <!-- 分页页码 -->
  <el-pagination
    v-model:current-page="pageParams.page"
    v-model:page-sizes="pageParams.limit"
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    :total="total"
  />
</template>

<script setup>
import {
  getSelectCategoryBrandAPI,
  deleteCategoryBrandAPI,
  getSelectAllAPI,
  getListAPI,
  postSaveCategoryBrandAPI,
  putUpdateCategoryBrandAPI,
} from '@/api/brand'
import { onMounted, ref, computed } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useApp } from '@/pinia/modules/app'
import { getSelectList } from '@/api/category'
//=================================查询==============================================
//数据总条数
const total = ref(0)
//分页数据模型
const pageParams = ref({
  page: 1,
  limit: 10,
})
//搜索和添加表单数据模型
const queryDto = ref({
  categoryId: '',
  brandId: '',
})
const searchCategoryIdList = ref([]) //存储选择的分类ID列表
//表格展示数据模型
const list = ref([])
// 分类树懒加载配置
const props = {
  lazy: true, // 启用懒加载
  value: 'id', // 绑定每个分类的id
  label: 'name', // 绑定每个分类的名称
  leaf: 'leaf', // 是否为叶子节点
  async lazyLoad(node, resolve) {
    //加载数据的方法
    if (typeof node.value == 'undefined') {
      node.value = 0
    }
    const { data } = await getSelectList(node.value) //查询商品分类菜单
    // 设置每个节点是否为叶子节点
    data.forEach(function(item) {
      //判断
      item.leaf = !item.hasChildren
    })
    //返回数据
    resolve(data)
  },
}
// 存储懒加载的配置
const categoryProps = ref(props)

// 调用后端接口,获取所有品牌数据
const getSelectAllData = async () => {
  const { code, data, message } = await getListAPI()
  // 将获取到的品牌数据赋值给brandList
  brandList.value = data
}
// 定义数据模型
const brandList = ref([]) // 存储品牌列表

//==============搜索按钮事件==================
const searchCategoryBrand = () => {
  //调用查询接口
  getSelectCategoryBrandData()
}
//==============重置按钮事件===============
const resetData = () => {
  searchCategoryIdList.value = []
  queryDto.value = {}
  //调用查询接口
  getSelectCategoryBrandData()
}
//======调用后端查询接口=======
const getSelectCategoryBrandData = async () => {
  if (searchCategoryIdList.value.length === 3) {
    // 如果选择了完整的分类，设置查询条件中的分类ID
    //这里的下标是从0开始的
    queryDto.value.categoryId = searchCategoryIdList.value[2]
  }
  const { code, data, message } = await getSelectCategoryBrandAPI(
    pageParams.value.page,
    pageParams.value.limit,
    queryDto.value
  )
  list.value = data.list
  total.value = data.total
}

onMounted(() => {
  //查询分类品牌
  getSelectCategoryBrandData()
  //查询品牌
  getSelectAllData()
})
//===========================添加or修改表单==========================================
//添加表单数据模型
const categoryBrand = ref({
  id: '',
  brandId: '', //品牌id
  categoryId: '', //分类id列表
})

//控制弹窗显示数据模型
const dialogVisible = ref(false)
//弹窗表单标题
const title = ref('')
//添加按钮事件
const addShow = () => {
  categoryBrand.value = {}
  title.value = '添加表单'
  dialogVisible.value = true
}

//提交按钮事件,调用后端接口
const submit = async () => {
  if (categoryBrand.value.brandId === '') {
    ElMessage.info('品牌信息必须选择')
    return
  }
  //categoryId为数组：[1,2,3]
  if (categoryBrand.value.categoryId.length !== 3) {
    ElMessage.info('分类信息必须选择')
    return
  }
  //后端只需要三级分类id
  categoryBrand.value.categoryId = categoryBrand.value.categoryId[2]
  //判断id是否存在,不存在,添加反之修改
  if (!categoryBrand.value.id) {
    const { code, data, message } = await postSaveCategoryBrandAPI(
      categoryBrand.value
    )
    if (code === 200) {
      ElMessage.success('添加成功!')
      dialogVisible.value = false
      getSelectCategoryBrandData()
    }
  } else {
    const { code, data, message } = await putUpdateCategoryBrandAPI(
      categoryBrand.value
    )
    if (code === 200) {
      ElMessage.success('修改成功!')
      dialogVisible.value = false
      getSelectCategoryBrandData()
    }
  }
}
//========================修改表单===========================================
//进入修改表单
const updateShow = row => {
  title.value = '修改表单'
  dialogVisible.value = true
  categoryBrand.value = { ...row }
}
//======================删除分类品牌==================================
const remove = row => {
  //调用后台接口
  ElMessageBox.confirm('是否确定删除?', '删除弹窗', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const { code } = await deleteCategoryBrandAPI(row.id)
    if (code === 200) {
      ElMessage.success('删除成功!')
      pageParams.value.page = 1
      getSelectCategoryBrandData()
    }
  })
}
///////////////////////////////////////////////////////////////////////////////文件上传
// 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
const headers = {
  token: useApp().authorization.token,
}

// 图像上传成功以后的事件处理函数
const handleAvatarSuccess = (response, uploadFile) => {
  categoryBrand.value.logo = response.data
}
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
